<template>
  <div class="energy-common page-basicment">
    <div class="main">
      <div class="common-title mb15">告警统计</div>
      <el-row type="flex" class="mb15">
        <el-form :inline="true">
          <el-form-item label="时间：" style="margin-bottom: 0px">
            <el-radio-group
              @change="getTime"
              v-model="searchStatistics.dateType"
              size="small"
            >
              <el-radio-button label="0">今天</el-radio-button>
              <el-radio-button label="1">昨天</el-radio-button>
              <el-radio-button label="7">最近7天</el-radio-button>
              <el-radio-button label="30">最近30天</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="日期："
            style="margin-bottom: 0px"
            label-width="70px"
          >
            <el-date-picker
              v-model="searchStatistics.time"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              size="mini"
              :clearable="false"
              @change="changeTime"
            >
            </el-date-picker>
          </el-form-item>
          <!-- <el-form-item
            label="资产："
            style="margin-bottom: 0px"
            label-width="70px"
          >
            <el-select
              style="width: 157px; margin-right: 15px"
              class="common-prefix-select"
              v-model="search.dicBh"
              size="mini"
            >
              <el-option
                v-for="item in gxOption"
                :key="item.id"
                :label="item['key_value']"
                :value="item['key_value']"
              />
            </el-select>
          </el-form-item> -->
        </el-form>
      </el-row>

      <div class="layer-box">
        <div class="layer-item bd1">
          <img lass="img" :src="require(`@/assets/img/img1.png`)" />
          <div class="layer-content">
            <span class="item-title">未处理告警数</span>
            <span class="item-count">{{count.abnormal}}</span>
          </div>
        </div>
        <div class="layer-item bd2">
          <img lass="img" :src="require(`@/assets/img/img2.png`)" />
          <div class="layer-content">
            <span class="item-title">已处理告警数</span>
            <span class="item-count">{{count.normal}}</span>
          </div>
        </div>
        <div class="layer-item bd3">
          <img lass="img" :src="require(`@/assets/img/img3.png`)" />
          <div class="layer-content">
            <span class="item-title">告警总数</span>
            <span class="item-count">{{ count.total }}</span>
          </div>
        </div>
      </div>

      <div class="chart-box">
        <div class="chart-item">
          <div class="chart-title">工序告警分布</div>
          <div class="chart-content" ref="chart1"></div>
        </div>
        <div class="chart-item">
          <div class="chart-title">设备告警分布</div>
          <div class="chart-content" ref="chart2"></div>
        </div>
        <div class="chart-item">
          <div class="chart-title">告警等级分布</div>
          <div class="chart-content" ref="chart3"></div>
        </div>
      </div>
    </div>
    <div class="main" style="margin-top: 20px">
      <div class="common-title mb15">告警明细</div>
      <el-row type="flex" class="mb15">
        <el-form :inline="true">
          <el-form-item label="对象：" style="margin-bottom: 0px">
            <el-form-item prop="dicBh" :show-message="false">
              <el-select
                v-model="search.dicBh"
                placeholder="选择工序"
                size="small"
                style="width: 157px; margin-right: 15px"
                clearable
                @change="changeGX"
              >
                <el-option
                  v-for="(item, index) in gxOption"
                  :key="index"
                  :label="item['key_value']"
                  :value="item['key_value']"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="params" :show-message="false">
              <el-cascader
                v-model="search.params"
                ref="cascader"
                placeholder="选择参数类型"
                size="small"
                :options="options"
                :props="cascaderProps"
                style="width: 240px"
                collapse-tags
                clearable
              ></el-cascader>
            </el-form-item>
          </el-form-item>
          <el-form-item
            label="等级："
            style="margin-bottom: 0px"
            label-width="70px"
          >
            <el-input
              placeholder="请输入事件等级"
              size="mini"
              v-model="search.level"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="mini" type="primary" @click="onSearch"
              >查询</el-button
            >
            <el-button size="mini" @click="resetForm()">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <div class="common-table" ref="chartTable">
        <el-table
          :data="tableData"
          style="width: 100%"
          :max-height="tableHeight"
        >
          <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
          <el-table-column prop="alarmName" label="告警名称" align="center" />
          <el-table-column prop="dicBh" label="工序" align="center" />
          <el-table-column prop="devSn" label="设备" align="center" />
          <el-table-column prop="csName" label="参数名称" align="center"/>
          <!-- <el-table-column prop="cs" label="参数" align="center"/> -->
          <el-table-column prop="collect" label="采集值" align="center" />
          <el-table-column prop="operator" label="操作符" align="center">
            <template slot-scope="{ row }">
              <div v-if="row.operator==0"> > </div>
              <div v-if="row.operator==1"> < </div>
              <div v-if="row.operator==2"> = </div>
              <div v-if="row.operator==3"> >= </div>
              <div v-if="row.operator==4"> <= </div>
              <div v-if="row.operator==5"> != </div>
            </template>
          </el-table-column>
          <el-table-column prop="standard" label="标准值" align="center" />
          <el-table-column prop="ruleName" label="触发规则" align="center" />
          <el-table-column prop="level" label="事件等级" align="center" />
          <el-table-column prop="status" label="告警状态" align="center" >
            <template slot-scope="{ row }">
               <el-tag
                size="mini"
                class="table-tag"
                :type="!row.status==1?'info':'warning'"
                >{{row.status==1?'未处理':'已处理'}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="告警时间" align="center" />
          <!-- <el-table-column prop="createTime" label="告警时长" align="center" /> -->
          <el-table-column prop="note" label="备注" align="center" />
          <el-table-column prop="action" label="操作" width="120px" align="center">
             <template slot-scope="{ row }">
              <el-button
                v-if="row.status==1"
                type="text"
                icon="el-icon-remove"
                @click="onOff(row)"
                >关闭告警</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="common-pagination">
        <el-pagination
          background
          layout="prev, pager, next, sizes, jumper"
          :page-size="search.pageSize"
          :current-page.sync="search.pageNum"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>

import { getAlarmConfig, apiAlarmConfig, getAlarmStatistical } from '@/api/alarm';
import moment from 'moment';
import {
  getSysDict,
  getParams1,
  getParams2,
  getSysDictByName,
} from '@/api/common';
export default {
  components: {  },
  data() {
    return {
      active: 'first',
      type: 'bar',
      //统计筛选
      searchStatistics: {
        dateType: 0,
        time: [],
      },
      search: {
        level: '',
        params: [], //设备参数
        dicBh: '', //工序
        pageNum: 1,
        pageSize: 10,
      },
      total: 10,
      loading: false,
      tableData: [],
      tableHeight: 468,
      count: {abnormal: 0, normal: 0, total: 0},
      equipOption: [],
      cascaderProps: {
        lazy: true,
        multiple: false,
        label: 'label',
        lazyLoad: async (node, resolve) => {
          if (node.level) {
            let form = {
              gongxu: node.data.gongxu,
              cs_type: node.data.cs_type,
            };
            const { data } = await getParams2(form);
            data.map((item) => {
              item.label = item['cs_name'];
              item.value = item['cs'];
              item.leaf = true;
            });
            resolve(data);
          }
        },
      },
      options: [],
      chart1:null,
      chart2:null,
      chart3:null,
    };
  },
  watch: {
    type: function (val) {
      // this.setChart(val);
    },
  },
  computed: {
    gxOption() {
      return this.$store.getters.gxOption;
    },
    // cjOption() {
    //   return this.$store.getters.cjOption;
    // },
  },
  created() {
    this.getTime(0)
    this.getTableData();
  },
  mounted() {
  },
  methods: {
    async changeGX(val) {
      this.getParams(val);
      this.search.devSn = [];
      if (val) {
        const res = await getSysDictByName(val + '设备');
        if (res.code == 1) {
          let bh = res.data.dataList[0]['bh'];
        }
      }
    },
    async getParams(val) {
      const { data } = await getParams1({ gongxu: val });
      let arr = [];
      data.map((item) => {
        let obj = Object.assign({}, item);
        obj.label = item.cs_type;
        obj.value = item.cs_type;
        arr.push(obj);
      });
      this.options = arr;
    },
    resetForm() {
      this.search = {
        level: '',
        params: [],
        dicBh: '',
        pageNum: 1,
        pageSize: 10,
      };
      this.getTableData();
    },
    onSearch() {
      this.search.pageNum = 1;
      this.getTableData();
    },
    //获取统计数据
    async getData() {
      let data = {}
      if(this.searchStatistics.time.length>0){
        data.startTime = this.searchStatistics.time[0]
        data.endTime = this.searchStatistics.time[1]
      }
      this.getLine('gongxu',data)
      this.getLine('fuji',data)
      this.getLine('level',data)
      let res = await getAlarmConfig('count', data);
      this.count = res.data;
    },
    async getTableData() {
      let form = Object.assign({}, this.search);
      form.devSn = form.params.length > 0 ? form.params[1] : '';
      delete form.params;
      const res = await getAlarmConfig('page', form);
      if (res.code == 1) {
        this.tableData = res.data.dataList;
        this.total = res.data.total;
      }
    },
    // 日期选择
    changeTime() {
      this.searchStatistics.dateType = '';
      let arr = [0, 1, 7, 30];
      arr.forEach((item) => {
        let time = this.getTime(item, false);
        if (
          JSON.stringify(time) == JSON.stringify(this.searchStatistics.time)
        ) {
          this.searchStatistics.dateType = item;
          return false;
        }
      });
      this.getData();
    },
    getTime(val, isSet = true) {
      console.log(val);
      const Format = 'YYYY-MM-DD';
      let startData = moment().subtract(val, 'days');
      let endData = moment();
      if (val == 1) endData = endData.subtract(val, 'days');
      let time = [startData.format(Format), endData.format(Format)];
      if (isSet) {
        this.searchStatistics.time = time;
        this.getData();
      }
      return time;
    },
    handleSizeChange(val) {
      this.search.pageNum = 1;
      this.search.pageSize = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.search.pageNum = val;
      this.getTableData();
    },
    //关闭告警
    onOff(data){
      this.$confirm('是否确认关闭告警吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        apiAlarmConfig('record/off',{
          id:data.id
        }).then((res) => {
          if (res.code == 1) {
            this.$message({
              message: '关闭成功',
              iconClass: 'el-icon-success',
              customClass: 'common-message',
            });
            this.getTableData()
          }
        });
      });
    },
    async getLine(cmd ,search) {
      const res = await getAlarmStatistical(cmd,search);
      if (res.code == 1) {
        let { data } = res;
        let chartData = {
          xAxis: [],
          yAxis: []
        };
        data.map(item => {
          chartData.xAxis.push(item.name);
          chartData.yAxis.push(item.number);
        });
        let chart = 'chart1'
        let xName = '工序'
        switch (cmd) {
          case 'fuji':
            chart = 'chart2'
            xName = '设备'
            break;
          case 'level':
            chart = 'chart3'
            xName = '等级'
            break;
          default:
            chart= 'chart1'
            xName = '工序'
            break;
        }
        this.setBarChart(chartData,chart,xName);
      }
    },
    setBarChart(data,chart,xName) {
      this[chart] = this.$echarts.init(this.$refs[chart]);

      let option = {
        grid: {
          left: '30px',
          right: '50px'
        },
        tooltip: {
          trigger: 'axis',
          textStyle: {
            fontSize: 13
          },
          padding: 10,
          backgroundColor: 'rgba(66, 66, 89, 0.8)',
          formatter: function(params) {
            var result =
              '<div style="font-size:14px;font-weight:600;margin-bottom:4px">' +
              params[0].axisValue +
              '</div>';
            result +=
              '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' +
              params[0].color +
              '"></span>';
            result += '告警数：' + params[0].data ;
            return result;
          }
        },
        xAxis: {
          type: 'category',
          name: xName,
           nameTextStyle: { color: '#292B3D' },
          data: data.xAxis,
          axisTick: { show: false },
          axisLine: { lineStyle: { color: 'rgba(225,231,235)' } },
          axisLabel: { color: '#606D86' }
        },
        yAxis: {
          type: 'value',
          name: '告警数',
          nameTextStyle: { color: '#292B3D' },
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: { color: '#606D86' },
          splitLine: {
            lineStyle: {
              type: 'dotted',
              color: 'rgba(65, 97, 128, 0.15)'
            }
          }
        },
        series: [
          {
            data: data.yAxis,
            type: 'bar',
            barWidth: 25,
            color: '#5B8FF9'
          }
        ]
      };
      this[chart].setOption(option);
      var _this = this;
      window.addEventListener('resize', function() {
        if(_this.chart1) _this.chart1.resize();
        if(_this.chart2) _this.chart2.resize();
        if(_this.chart3) _this.chart3.resize();
      });
    },
  },
};
</script>

<style lang="scss">
@import '@/assets/css/energy.scss';
.page-basicment {
  background-color: #f6f9fc;
  overflow:scroll !important;
  .main {
    background: #ffffff;
    height: auto !important;
  }
  .layer-box {
    display: flex;
    flex-direction: row;
    .layer-item {
      display: flex;
      flex: 1;
      height: 132px;
      margin: 0 25px 25px 0;
      padding: 0px 0 0 46px;
      box-sizing: border-box;
      align-items: center;
      box-shadow: 0px 7px 9px 0px rgb(212 214 231 / 61%);
      border-radius: 4px;
      .img {
        width: 69px;
        height: 62px;
      }
      .layer-content {
        display: flex;
        flex-direction: column;
        color: #ffffff;
        margin-left: 46px;
        .item-title {
          height: 22px;
          font-size: 16px;
          line-height: 22px;
          font-family: PingFangSC-Medium;
          font-weight: bold;
        }
        .item-count {
          font-family: PingFangSC-Medium;
          font-size: 48px;
          font-weight: bold;
        }
      }
      &.bd1 {
        background-color: #f47575;
      }
      &.bd2 {
        background-color: #60ce7a;
      }
      &.bd3 {
        background-color: #4b90e4;
        margin-right: 0;
      }
    }
  }
  .chart-box {
    display: flex;
    .chart-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      margin: 0 25px 25px 0;
      .chart-title {
        font-size: 14px;
        background: #f6f6f6;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #292b3d;
        height: 40px;
        line-height: 40px;
        text-align: center;
      }
      .chart-content {
        height: 267px;
        padding: 0 10px;
        // border: 1px solid #f47575;
      }
      &:last-child {
        margin-right: 0;
      }
    }
  }
}
</style>
